<template>
  <div class="dashboard-container">
    <FeatureHeader img="https://cdn-icons-png.flaticon.com/512/1827/1827379.png" title="仪表盘" />
    
    <!-- 图表控制区域 -->
    <el-card class="chart-control-card" v-loading="chartLoading">
      <div slot="header" class="chart-header">
        <span>员工分布统计</span>
        <div style="float: right;">
          <!-- 图表类型切换 -->
          <el-select v-model="chartType" placeholder="请选择图表类型" size="small" style="margin-right: 10px;">
            <el-option label="柱状图" value="bar"></el-option>
            <el-option label="折线图" value="line"></el-option>
            <el-option label="饼图" value="pie"></el-option>
          </el-select>

          <!-- 时间筛选 -->
          <el-date-picker
            v-model="selectedDate"
            :type="datePickerType"
            :placeholder="datePickerPlaceholder"
            size="small"
            @change="handleDateChange"
            :clearable="false"
            format="yyyy-MM"
            value-format="yyyy-MM"
          ></el-date-picker>
        </div>
      </div>

      <!-- 图表容器 -->
      <div ref="chart" class="dashboard-chart" :style="{ height: chartHeight + 'px' }"></div>
    </el-card>

    <!-- 快捷菜单 -->
    <el-row :gutter="20" style="margin-top: 32px;">
      <el-col :span="6" v-for="(item, index) in menuItems" :key="index">
        <el-card class="menu-card" @click.native="handleMenuClick(item.path)">
          <div class="menu-item">
            <i :class="[item.icon, 'menu-icon']"></i>
            <span>{{ item.title }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import FeatureHeader from '@/components/FeatureHeader.vue'
import * as echarts from 'echarts'
import { mapState, mapActions } from 'vuex'

export default {
  name: 'Dashboard',
  components: { FeatureHeader },
  data() {
    return {
      chart: null,
      chartLoading: true,
      chartHeight: 400,
      chartType: 'bar', // 当前图表类型
      selectedDate: new Date().toISOString().slice(0, 7), // 默认显示当前月份
      datePickerType: 'month', // 可选值：'month', 'year'
      datePickerPlaceholder: '请选择月份',
      menuItems: [
        { title: '人员管理', icon: 'el-icon-user', path: '/employee' },
        { title: '部门管理', icon: 'el-icon-office-building', path: '/department' },
        { title: '职位管理', icon: 'el-icon-suitcase', path: '/position' },
        { title: '工资管理', icon: 'el-icon-money', path: '/salary' },
        { title: '出差管理', icon: 'el-icon-location', path: '/business-trip' },
        { title: '公告管理', icon: 'el-icon-bell', path: '/announcement' }
      ],
      // 模拟员工变动数据
      mockEmployeeTrendData: {
        '2024-01': { hired: 10, left: 2 },
        '2024-02': { hired: 12, left: 3 },
        '2024-03': { hired: 8, left: 1 },
        '2024-04': { hired: 15, left: 5 },
        '2024-05': { hired: 13, left: 4 },
        '2024-06': { hired: 11, left: 2 },
        '2024-07': { hired: 14, left: 3 },
        '2024-08': { hired: 16, left: 2 },
        '2024-09': { hired: 9, left: 1 },
        '2024-10': { hired: 18, left: 4 },
        '2024-11': { hired: 17, left: 3 },
        '2024-12': { hired: 19, left: 2 }
      }
    }
  },
  computed: {
    ...mapState({
      employeeList: state => state.employee.list
    }),

    departmentEmployeeCount() {
      const counts = {}
      this.employeeList.forEach(employee => {
        if (employee.department) {
          counts[employee.department] = (counts[employee.department] || 0) + 1
        }
      })
      return counts
    },

    chartOptions() {
      const departments = Object.keys(this.departmentEmployeeCount)
      const counts = Object.values(this.departmentEmployeeCount)

      let option = {}

      switch (this.chartType) {
        case 'bar':
          option = {
            tooltip: {},
            xAxis: { type: 'category', data: departments },
            yAxis: { type: 'value' },
            series: [{ type: 'bar', data: counts }]
          }
          break
        case 'line':
          option = {
            tooltip: {},
            xAxis: { type: 'category', data: departments },
            yAxis: { type: 'value' },
            series: [{ type: 'line', data: counts }]
          }
          break
        case 'pie':
          option = {
            tooltip: { trigger: 'item' },
            legend: { show: true },
            series: [
              {
                name: '部门人数',
                type: 'pie',
                radius: '50%',
                data: departments.map((name, i) => ({ name, value: counts[i] })),
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          break
        default:
          option = {
            tooltip: {},
            xAxis: { data: departments },
            yAxis: {},
            series: [{ type: 'bar', data: counts }]
          }
      }

      // 设置标题统一
      option.title = { text: '员工部门分布' }

      return option
    },

    // 获取当前选中日期的员工趋势数据
    currentTrendData() {
      return this.mockEmployeeTrendData[this.selectedDate] || { hired: 0, left: 0 }
    }
  },
  watch: {
    chartOptions: {
      deep: true,
      handler(newOptions) {
        if (this.chart) {
          this.chart.setOption(newOptions)
        }
      }
    }
  },
  mounted() {
    // 计算图表容器高度
    this.calculateChartHeight()
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize)
    
    // 确保DOM和数据都准备好后再初始化图表
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    ...mapActions({
      fetchList: 'announcement/fetchList',
      addAnnouncement: 'announcement/addAnnouncement',
      editAnnouncement: 'announcement/editAnnouncement',
      deleteAnnouncement: 'announcement/deleteAnnouncement'
    }),
    calculateChartHeight() {
      // 根据窗口高度动态计算图表高度
      const windowHeight = window.innerHeight
      this.chartHeight = Math.max(400, windowHeight * 0.5)
    },
    handleResize() {
      this.calculateChartHeight()
      this.resizeChart()
    },
    async initChart() {
      try {
        this.chartLoading = true
        
        // 等待数据加载完成
        await this.$store.dispatch('employee/fetchList')
        
        // 确保DOM已经渲染
        await this.$nextTick()
        
        if (!this.$refs.chart) {
          console.warn('图表容器未找到')
          return
        }
        
        // 确保echarts实例不存在时才创建
        if (!this.chart) {
          this.chart = echarts.init(this.$refs.chart)
        }
        
        // 设置图表配置
        this.chart.setOption(this.chartOptions)
        
      } catch (error) {
        console.error('初始化图表失败:', error)
        this.$message.error('图表加载失败，请刷新页面重试')
      } finally {
        this.chartLoading = false
      }
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    handleMenuClick(path) {
      this.$router.push(path)
    },
    handleDateChange(value) {
      this.selectedDate = value
      this.updateChartWithSelectedDate()
    },
    updateChartWithSelectedDate() {
      // 这里可以调用API获取指定时间的员工数据
      console.log(`加载 ${this.selectedDate} 的员工数据`)
    },
    handleDelete(row) {
      this.$confirm('确认删除该公告?', '提示', {
        type: 'warning'
      }).then(() => {
        this.deleteAnnouncement(row.id).then(() => {
          this.$message.success('删除成功')
        }).catch(error => {
          console.error('删除公告失败:', error)
          this.$message.error('删除失败，请重试')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.chart-control-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dashboard-chart {
  width: 100%;
  min-height: 400px;
  transition: height 0.3s ease;
}

.menu-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}
.menu-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
.menu-icon {
  font-size: 48px;
  margin-bottom: 10px;
  color: #409eff;
}
.menu-item span {
  font-size: 16px;
  color: #303133;
}
</style>